import { PlusOutlined, ExclamationCircleOutlined, EditOutlined } from '@ant-design/icons';
import {
  Button,
  Divider,
  message,
  Input,
  Drawer,
  Table,
  Tabs,
  Card,
  Modal,
  AutoComplete,
  Form,
  Select,
  Popconfirm,
  Popover,
} from 'antd';
import React, { useState, useRef } from 'react';
import SyntaxHighlighter from 'react-syntax-highlighter';
import { dark } from 'react-syntax-highlighter/dist/esm/styles/hljs';
import { CopyOutlined } from '@ant-design/icons';
import CopyToClipboard from 'react-copy-to-clipboard';
import { FormattedMessage, history, Link } from 'umi';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import { getPassword, getHarborAddress, editHarborDesc,deletePublicHarbor, getPublicHarborAccess } from './service';
import { getPublicImageList, deleteImage } from '../Harbor/service';

import { SORTS } from '@/utils/const';
//权限组件
import { AuthzHOC, AuthzProvider, useCheckAuth, checkAuth } from '@apulis/authz';

import '@/assets/css/table.less';
import format from '@/utils/format';
const { TextArea } = Input;

const NameSpace = (props) => {
  const [showNameSpace, setShowNameSpace] = useState(false);
  const [newNameSpace, setNewNameSpace] = useState('');
  const [tab, setTab] = useState(props.location.query.tab);
  const [showPull, setShowPull] = useState(false);
  const [nameSpace, setNameSpace] = useState([]);
  const [showLogin, setShowLogin] = useState(false);
  const [loginCmd, setLoginCmd] = useState('');
  const [expires_at, setExpires] = useState(0);
  const [code, setCode] = useState('');
  const [showEdit, setShowEdit] = useState(false);
  const [nowEditId, setNowEditId] = useState(0);

  const [descForm] = Form.useForm();

  const columns = [
    {
      title: React.$i18n('镜像名称'),
      dataIndex: 'imageName',
      render: (text, r) => {
        return <Link to={`/publicImageDetail?id=${r.id}`}>{text}</Link>
        // return <a href={`/publicImageDetail?id=${r.id}`}>{text}</a>;
      },
    },

    {
      title: React.$i18n('版本数'),
      dataIndex: 'versionCount',
    },
    {
      title: React.$i18n('描述'),
      dataIndex: 'description',
      render: (text, record) => {
        return (
          <div>
            <Popover content={
              <div style={{width: '300px', wordBreak: 'break-all'}}>
                {text}
              </div>
            }>
              <span className='textEllipsis' style={{width: '300px', display: 'inline-block'}}>
                {text}{' '}
              </span>
            </Popover>
            <span>
              <AuthzHOC permission="/apharbor/api/v1/images/image/editDescription" action={['post']}>
                <EditOutlined  onClick={() => {editLine(record);}} style={{ cursor: 'pointer' }} />
              </AuthzHOC>
            </span>
          </div>
        );
      },
    },
    {
      title: React.$i18n('更新时间'),
      dataIndex: 'updateAt',
      render: (text) => format(text),
      sorter: true,
      // sorter: (a, b) => a.createAt - b.createAt,
    },
    {
      title: React.$i18n('操作'),
      render(text, record) {
        return (
          <AuthzHOC permission="/apharbor/api/v1/images/publicImage/{id}" action={['delete']}>
            <Popconfirm
              title="确认删除?"
              onConfirm={() => {
                deletePublicHarbor(record.id).then((res) => {
                  if (res.code == 0) {
                    message.success('删除成功');
                  }
                  ref.current.reload();
                });
              }}
              okText="是"
              cancelText="否"
            >
              <a style={{ color: 'red' }} type="text">
                删除
              </a>
            </Popconfirm>
          </AuthzHOC>
        );
      },
    },
  ];

  function getLoginPass() {
    // getPassword('public').then((res) => {
    getPublicHarborAccess().then((res) => {
      setLoginCmd(res.data.logincmd);
      setExpires(res.data.expires_at);
      setShowLogin(true);
    });
  }
  let titleStyle = {
    fontWeight: 'bold',
    marginBottom: '10px',
  };
  let contentStyle = {
    marginBottom: '10px',
  };

  function editLine(record) {
    if (record.description) {
      descForm.setFieldsValue({
        description: record.description,
      });
    }
    setNowEditId(record.id);
    setShowEdit(true);
  }
  // const code = `$ sudo docker tag [{镜像名称}:{版本名称}] ${baseLine}/{镜像名称}:{版本名称}\n$ sudo docker push ${baseLine}/{镜像名称}:{版本名称}`;
  const ref = React.useRef();
  return (
    <div className="name-space">
      <PageContainer>
        {/* 添加基础信息 */}
        <Card bodyStyle={{ padding: '0 16px' }}>
          <ProTable
            className="left-toolbar"
            options={false}
            actionRef={ref}
            search={false}
            rowKey={(r) => r.id}
            cardProps={{
              bodyStyle: { padding: 0 },
            }}
            request={async (params, sorter) => {
              const sorterStr = sorter.updateAt ? `updateAt|${SORTS.get(sorter.updateAt)}` : ''
              const res = await getPublicImageList({
                pageNum: params.current,
                pageSize: params.pageSize,
                sort: sorterStr,
              });
              if (res && res.code === 0) {
                return {
                  data: res.data.items,
                  success: true,
                  total: res.data.total,
                };
              }
            }}
            toolBarRender={() => [
              <div>
                <AuthzHOC permission="/apharbor/api/v1/harbor/getPublicHarborAccess" action={['get']}>
                  <Button
                    type="primary"
                    onClick={() => {
                      getHarborAddress('public').then((res) => {
                        console.log(res);
                        if (res && res.code == 0) {
                          const address = res.data.harborAddress;
                          const code = `$ sudo docker tag {镜像名称}:{版本名称} ${address}/{镜像名称}:{版本名称}\n$ sudo docker push ${address}/{镜像名称}:{版本名称}`;
                          setCode(code);
                          setShowPull(true);
                        } else {
                          message.error('获取harborAddress失败');
                        }
                      });
                    }}
                    style={{ marginRight: '10px' }}
                  >
                    客户端上传
                  </Button>
                </AuthzHOC>
              </div>,
            ]}
            columns={columns}
          />
        </Card>
      </PageContainer>
      <Modal
        title="客户端上传"
        width="800px"
        visible={showPull}
        footer={null}
        onCancel={() => {
          setShowPull(false);
        }}
        maskClosable={false}
      >
        <div className="title" style={titleStyle}>
          前提条件：
        </div>
        <div className="content" style={contentStyle}>
          准备一台计算机,要求安装的容器引擎版本必须为1.11.2及以上
        </div>
        <div className="title" style={titleStyle}>
          操作步骤：
        </div>
        <div className="content" style={contentStyle}>
          Step 1. 以root用户登录容器引擎所在的虚拟机
        </div>
        <div className="content" style={contentStyle}>
          Step 2. 获取登录访问指令，并复制到节点上执行{' '}
          <span
            style={{ color: '#1A90FF', cursor: 'pointer' }}
            onClick={() => {
              getLoginPass();
            }}
          >
            生成临时登录指令
          </span>
        </div>
        <div className="content" style={contentStyle}>
          Step 3. 上传镜像
        </div>
        <SyntaxHighlighter language="bash" style={dark}>
          {code}
        </SyntaxHighlighter>
      </Modal>
      <Modal
        title="登录指令"
        width="800px"
        visible={showLogin}
        footer={null}
        onCancel={() => {
          setShowLogin(false);
        }}
        maskClosable={false}
      >
        <div style={{ width: '750px', marginBottom: '10px' }} className="pre-block">
          <div>
            {' '}
            {loginCmd}{' '}
            <CopyToClipboard
              text={loginCmd}
              onCopy={() => {
                message.info('复制成功');
              }}
            >
              <CopyOutlined style={{ cursor: 'pointer' }} />
            </CopyToClipboard>
          </div>
        </div>

        <p>过期时间:{format(expires_at * 1000)}</p>
      </Modal>
      <Modal
        title="编辑描述"
        width="800px"
        visible={showEdit}
        footer={null}
        onCancel={() => {
          setShowEdit(false);
          setNowEditId('');
          descForm.setFieldsValue({
            description: '',
          });
        }}
        maskClosable={false}
      >
        <Form
          name="editDescription"
          labelCol={{ span: 3 }}
          wrapperCol={{ span: 20 }}
          initialValues={{ remember: true }}
          onFinish={(info) => {
            //可判断描述是否有变更，有改再发送请求
            editHarborDesc({
              description: info.description,
              imageId: nowEditId,
            }).then((res) => {
              if (res.code == 0) {
                ref.current.reload();
                message.success('修改成功');
                setNowEditId(0);
                setShowEdit(false);
                descForm.setFieldsValue({
                  description: '',
                });
              }
            });
          }}
          form={descForm}
        >
          <Form.Item
            label="描述详情"
            name="description"
            rules={[{ message: '请输入描述详情' }]}
          >
            <TextArea rows={4} />
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 4, span: 20 }}>
            <Button type="primary" htmlType="submit">
              提交
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default NameSpace;
